package org.study.ratelimiter.value.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.study.ratelimiter.Constants;
import org.study.ratelimiter.annotation.DoRateLimiter;
import org.study.ratelimiter.value.IValveService;

import java.lang.reflect.Method;

@Slf4j
public class RateLimiterValve implements IValveService {
    @Override
    public Object access(ProceedingJoinPoint jp, Method method, DoRateLimiter doRateLimiter, Object[] args) throws Throwable {
        double second = doRateLimiter.permitsPerSecond();
        // 判断当前是否开始限流
        if (second == 0) {
            // 未开始限流,则直接去执行相关的逻辑
            return jp.proceed();
        }
        // 获取当前的执行类名称
        String clsName = jp.getTarget().getClass().getName();
        log.info("clsName:", clsName);
        String methodName = method.getName();
        log.info("methodName:", methodName);
        String key = clsName+"."+methodName;
        // 桶里没有
        if(null ==Constants.rateLimiterMap.get(key)){
            // 往桶中插入 key 和 RateLimiter对象
            Constants.rateLimiterMap.put(key, RateLimiter.create(doRateLimiter.permitsPerSecond()));
        }
        // 在从桶中获取
        RateLimiter rateLimiter = Constants.rateLimiterMap.get(key);
        if(rateLimiter.tryAcquire()){
            // 未达到量
          return   jp.proceed();
        }
        // 达到了标准量 ，返回我们的数据
        return JSON.parseObject(doRateLimiter.returnJson(), method.getReturnType());
    }
}
